<?php

Raise::load('core.RaiseStaticClass');
Raise::load('core.IRaiseInitializable');
Raise::load('core.collection.RaiseTypedCollection');
Raise::load('core.ui.RaiseTemplate');
Raise::load('core.net.RaiseUrl');

class RaiseUrlRouteManager extends RaiseStaticClass implements IRaiseInitializable {

    const KEY = '_urlrouting_';

    /**
     * All defined url rewriting routes for the application
     * @var RaiseTypedCollection
     * @static
     */
    private static $routes;
    
    public static function initialize() {
        self::$routes = new RaiseTypedCollection('RaiseUrlRoute');
    }
    
    /**
     * Add a new routing entry
     * @param string $key
     * @param RaiseUrlRoute $route
     */
    protected static function add($key, $route){
        self::$routes->add($key, $route);
    }
    
    /**
     * Get all the routes
     * @return RaiseTypedCollection
     */
    public static function routes(){
        return self::$routes;
    }

    /**
     * Get a specific URL route with all the parameters prepared
     * @param string $key The identifier of the route
     * @param RaiseCollection|array $args (optional) The arguments to be passed to the page
     * @return string
     */
    public static function route($key, $args = array()){

        $route = self::$routes->get($key);
        if($route == null){
            throw new RaiseInvalidArgumentException('The routing $key value \'' . $key . '\' was not found in the routing collection.');
        }
        $t = new RaiseTemplate($route->rewrite());
        foreach($args as $k => $a){
            $t->fields()->add($k, RaiseUrl::encode($a));
        }

        return $t->parse();
    }
    
}